package com.hengtongxing.hejiayun_employee.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.hengtongxing.hejiayun_employee.MyApplication;
import com.hengtongxing.hejiayun_employee.R;
import com.hengtongxing.hejiayun_employee.login.LoginActivity;
import com.hengtongxing.hejiayun_employee.mine.UserAgreementActivity;
import com.hengtongxing.hejiayun_employee.utils.Dp2Px;
import com.hengtongxing.hejiayun_employee.utils.SPManager;
import com.hengtongxing.hejiayun_employee.utils.ScreenUtils;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.tencent.bugly.beta.ui.UILifecycleListener;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Author:HWC
 */
public class PrivacyDialog extends DialogFragment {


    @BindView(R.id.dialog_message)
    TextView dialogMessage;
    private Dialog dialog;
    Unbinder unbinder;
    private Context mContext;
    private static final String TAG = "AliPushInit";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initWindow();
        View view = inflater.inflate(R.layout.dialog_privacy, null);
        unbinder = ButterKnife.bind(this, view);
        mContext = getActivity();
        initView();
        return view;
    }

    public static PrivacyDialog newInstance() {
        PrivacyDialog fragment = new PrivacyDialog();
        return fragment;
    }

    //    初始化请求
    private void initView() {
        String str = getResources().getString(R.string.privacy);
        SpannableStringBuilder spannable = new SpannableStringBuilder(str);
        spannable.setSpan(new TextClick(1), 34, 40, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(new TextClick(2), 41, 47, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        dialogMessage.setMovementMethod(LinkMovementMethod.getInstance());
        dialogMessage.setText(spannable);
    }

    private class TextClick extends ClickableSpan {
        private int type;

        public TextClick(int type) {
            this.type = type;
        }

        @Override
        public void onClick(View widget) {
            if (isAdded()) {
                avoidHintColor(widget);
            }
            Intent intent = new Intent(getActivity(), UserAgreementActivity.class);
            intent.putExtra("type", type);
            startActivity(intent);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(getResources().getColor(R.color.color_blue2));
            ds.setUnderlineText(false);
            ds.clearShadowLayer();
        }
    }

    private void avoidHintColor(View view) {
        if (view instanceof TextView)
            ((TextView) view).setHighlightColor(getResources().getColor(android.R.color.transparent));
    }

    //设置window属性
    private void initWindow() {
        //去掉dialog的标题
        dialog = this.getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int) (ScreenUtils.getScreenWidth(mContext) - Dp2Px.dp2Px(65));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.dialog_negative, R.id.dialog_positive})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dialog_negative:
                dismiss();
                getActivity().finish();
                break;
            case R.id.dialog_positive:
                initCloudChannel(MyApplication.getApplication());
                initCrashReport();
                SPManager.getInstance().saveProtocol("true");
                dismiss();
                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
                break;
        }
    }

    /**
     * 初始化云推送通道
     *
     * @param applicationContext
     */
    public void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.d(TAG, "init cloudchannel success deviceId : " + pushService.getDeviceId());
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.d(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }

    /**
     * 腾讯bugly
     */
    public void initCrashReport() {
        Context context = MyApplication.getContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));

        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog;
        Beta.upgradeDialogLifecycleListener = new UILifecycleListener<UpgradeInfo>() {
            @Override
            public void onCreate(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onCreate");
            }

            @Override
            public void onStart(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onStart");
            }

            @Override
            public void onResume(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onResume" + upgradeInfo.upgradeType);
                View view_line = view.findViewById(R.id.view_line);
                if (upgradeInfo.upgradeType == 2) {
                    view_line.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPause(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onPause");
            }

            @Override
            public void onStop(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onStop");
            }

            @Override
            public void onDestroy(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onDestory");
            }
        };
        Bugly.init(MyApplication.getContext(), "9d72576b29", true);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
